package com.qpcy.controller;

import com.mybatisflex.core.query.QueryWrapper;
import com.qpcy.entity.Type;
import com.qpcy.service.TypeService;
import com.qpcy.utils.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

import static com.qpcy.entity.table.TypeTableDef.TYPE;

/**
 * 分类 控制层。
 *
 * @author LENOVO
 * @since 2024-10-19
 */
@RestController
@RequestMapping("/type")
public class TypeController {

    @Autowired
    private TypeService typeService;

    /**
     * 获取分类的一级分类
     *
     * @return
     */
    @GetMapping("/getFirst")
    public ResponseResult getFirst() {
        QueryWrapper queryWrapper = QueryWrapper.create()
                .eq(Type::getParentId, 0)
                .orderBy("CASE WHEN sort IS NULL THEN 1 ELSE 0 END")
                .orderBy(TYPE.SORT.asc());
        List<Type> list = typeService.list(queryWrapper);
        return ResponseResult.success(list);
    }

    /**
     * 获取当前一级分类的所有二级分类
     *
     * @param typeId
     * @return
     */
    @GetMapping("/getDetail")
    public ResponseResult getDetail(int typeId) {
        QueryWrapper queryWrapper = QueryWrapper.create()
                .eq(Type::getParentId, typeId)
                .orderBy("CASE WHEN sort IS NULL THEN 1 ELSE 0 END")
                .orderBy(TYPE.SORT.asc());
        return ResponseResult.success(typeService.list(queryWrapper));
    }

    @GetMapping("/getAll")
    public ResponseResult getAll() {
        return typeService.getAll();
    }

    /**
     * 新增分类
     *
     * @param type
     * @return
     */
    @PostMapping("/save")
    public ResponseResult save(@RequestBody Type type) {
        return ResponseResult.success(typeService.save(type));
    }

    /**
     * 修改分类信息
     *
     * @param type
     * @return
     */
    @PostMapping("/update")
    public ResponseResult update(@RequestBody Type type) {
        return ResponseResult.success(typeService.updateById(type));
    }

    /**
     * 删除分类
     *
     * @param typeId
     * @return
     */
    @PostMapping("/delete")
    public ResponseResult delete(int typeId) {
        return typeService.deleteById(typeId);
    }

}
